#!/usr/bin/env python
#coding: utf-8
from models import UserProfile
from functools import wraps
from django.utils.decorators import available_attrs
from django.http import Http404#, Http404

def get_user_profile(request):
	if request.user.is_authenticated():
		profile = request.session.get('user_profile', None)
		if not profile: 
			#profile = request.user.get_profile()
			try:
				profile = request.user.get_profile()
			except Exception as e:
				#request.user.DoesNotExist:
				#assert False
				profile = UserProfile(user = request.user)
				profile.save()
	else:
		profile = None
	return profile

def get_network_admin(request):
	profile = get_user_profile(request)
	if profile and profile.network_admin: return profile
	return None

def get_structure_admin(request):
	profile = get_user_profile(request)
	if profile and profile.structure_admin: return profile
	return None

def auth_user_required(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapped(request, *args, **kwargs):
        if request.user:
            profile = get_user_profile(request)
            if profile: 
                kwargs['profile'] = profile
                return func(request, *args, **kwargs)
        raise Http404()

    return wrapped

def get_prodinf_profile(request):
    return get_user_profile(request)

def prodinf_profile_required(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapped(request, *args, **kwargs):
        if request.user:
            profile = get_prodinf_profile(request)
            if profile: 
                kwargs['profile'] = profile
                return func(request, *args, **kwargs)
        raise Http404()
    return wrapped


# def auth_user_required(*args_, **kwargs_):
# 	def wrapper(func):
# 		def tmp(*args, **kwargs):
# 			request = args[0]
# 			if request.user:
# 				profile = get_user_profile(request)
# 				if profile: 
# 					kwargs['profile'] = profile
# 					return func(*args, **kwargs)
# 			raise Http404()
# 		return tmp
# 	return wrapper

def network_admin_required(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapped(request, *args, **kwargs):
        if request.user:
            profile = get_network_admin(request)
            if profile: 
                kwargs['profile'] = profile
                return func(request, *args, **kwargs)
        raise Http404()

    return wrapped

def structure_admin_required(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapped(request, *args, **kwargs):
        if request.user:
            profile = get_structure_admin(request)
            if profile: 
                kwargs['profile'] = profile
                return func(request, *args, **kwargs)
        raise Http404()

    return wrapped
